#!/usr/bin/env python
#coding=utf-8
# author:wade
# contact: 317909531@qq.com
# datetime:2020/3/28 11:23
import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException, AuthenticationFailed

from shareAPI2020TB import settings

"""
文件说明： 检查token的验证模块
"""

class JWTQueryParameAustentication(BaseAuthentication): #权限认证
    def authenticate(self, request):

        print('-----jwt-Start 验证token除湿模块')

        SALT = settings.SECRET_KEY
        # 获取token的值

        # 先判断头部有没有token，如果有，取出来token
        # 如果没有，查一下看看是否有请求字段里边的token，
        token = request.META.get('HTTP_TOKEN')  # 尝试获取头部信息，HTTP_前缀
        tokenFrom = "from HEAD"
        if not token and isinstance(request.data, dict):

            token = request.data.get('token')  # 尝试获取POST方法传来的token
            tokenFrom = "from DATA"
            if not token:
                tokenFrom = "缺少token字段，后台支持head和json方式提交token"
        print(f"【请求类型】:{request.META.get('CONTENT_TYPE')} 【令牌token】:{token} 【获得方式】:{tokenFrom}")

        payload = None
        msg = None
        try:
            payload = jwt.decode(token, key=SALT, verify=True)
        except jwt.exceptions.ExpiredSignatureError:
            msg = f"token失效"
            raise AuthenticationFailed({'code': 403, 'msg': msg})
        except jwt.exceptions.DecodeError:
            msg = f"token认证失败"
            raise AuthenticationFailed({'code': 403, 'msg': msg})
        except jwt.exceptions.InvalidTokenError:
            msg = f"非法token"
            raise AuthenticationFailed({'code': 403, 'msg': msg})

        print(payload['user_id'], payload['username'])

        return (payload, token)